package com.sxm.yiwei.activitis;

import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.SearchGridAdapter;
import com.sxm.yiwei.adapters.SearchListviewAdapter;
import com.sxm.yiwei.adapters.SearchShopAdapter;
import com.sxm.yiwei.beans.ServiceContent;
import com.sxm.yiwei.beans.ShopContent;
import com.sxm.yiwei.fragments.SearchCommentFragment;
import com.sxm.yiwei.fragments.SearchDistanceFragment;
import com.sxm.yiwei.fragments.SearchNumberFragment;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class HomeSearchActivity extends BaseActivity implements View.OnClickListener, PoiSearch.OnPoiSearchListener {

    private GridView fastgrid;
    private GridView historygrid;
    private TextView searchbutton;
    private LinearLayout fast;
    private LinearLayout history;
    private PullToRefreshListView listview;
    private SearchGridAdapter adapter;
    private TextView searchtype;
    private TextView assess;
    private TextView distance;
    private TextView number;
    private static int TYPE =0;
    private ImageView searchbackimg;
    private EditText searchcontent;
    private SharedPreferences sharedPreferences;
    public String token;
    public String userId;
    public String appId;
    public String longitude;
    public String latitude;
    public static String t;
    private List list1;
    private SearchListviewAdapter listviewAdapter;
    private SearchShopAdapter shopAdapter;
    private SearchListviewAdapter listviewAdapter1;
    private LinearLayout popbac;
    private TextView distancebt;
    private TextView numberbt;
    private TextView commentbt;
    private SearchDistanceFragment distanceFragment;
    private SearchNumberFragment numberFragment;
    private SearchCommentFragment commentFragment;
    private FrameLayout fragmentRoots;
    private LinearLayout searchtab;
    public int  condition = 1;
    public static String con;
    public static int fwpage = 1;
    private JSONArray data;
    private ListView locationlist;
    private double poilatitude1;
    private double poilongitude1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_search);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        Intent intent = getIntent();
        t = intent.getStringExtra("t");
        initsearchView();


        // 默认为0
        TYPE=0;
        distancebt.setSelected(true);
        viewFragment(0);
        if (t!=null){
            TYPE=3;
            fragmentRoots.setVisibility(View.VISIBLE);
            history.setVisibility(View.VISIBLE);
            fast.setVisibility(View.GONE);
            searchtab.setVisibility(View.VISIBLE);
            //searchServicehome(t,TYPE);
            con=t;
            searchcontent.setText(t);
            distanceFragment.searchService(fwpage);
        }else {
            con = String.valueOf(searchcontent.getText());
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }

    private void viewFragment(int i) {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        hideFragment(ft);
        switch (i){
            case 0:
                if (distanceFragment==null){
                    distanceFragment = new SearchDistanceFragment();
                    ft.add(R.id.search_fragment,distanceFragment);
                }else {
                    ft.show(distanceFragment);
                }
                break;
            case 1:
                if (numberFragment==null){
                    numberFragment = new SearchNumberFragment();
                    ft.add(R.id.search_fragment,numberFragment);
                }else {
                    ft.show(numberFragment);
                }
                break;
            case 2:
                if (commentFragment==null){
                    commentFragment = new SearchCommentFragment();
                    ft.add(R.id.search_fragment,commentFragment);
                }else {
                    ft.show(commentFragment);
                }
                break;
        }


        ft.commit();
    }

    private void hideFragment(FragmentTransaction ft) {
        if (distanceFragment!=null){
            ft.hide(distanceFragment);
        }else {}
        if (numberFragment!=null){
            ft.hide(numberFragment);
        }else {}
        if (commentFragment!=null){
            ft.hide(commentFragment);
        }else {}
    }

    private void initsearchView() {
        searchbackimg = (ImageView) findViewById(R.id.home_search_back);

        searchbutton = (TextView) findViewById(R.id.search_button);
        fast = (LinearLayout) findViewById(R.id.fast);
        history = (LinearLayout) findViewById(R.id.history);
        locationlist = (ListView) findViewById(R.id.locationpoi_listview);
        listview = (PullToRefreshListView) findViewById(R.id.listview);
        searchtype = (TextView) findViewById(R.id.search_type);
        searchcontent = (EditText) findViewById(R.id.search_searchcontent);
        distancebt = (TextView) findViewById(R.id.search_distancebt);
        numberbt = (TextView) findViewById(R.id.search_bunberbt);
        commentbt = (TextView) findViewById(R.id.search_commentbt);
        fragmentRoots = (FrameLayout) findViewById(R.id.search_fragment);
        searchtab = (LinearLayout) findViewById(R.id.search_tab);
        distancebt.setOnClickListener(this);
        numberbt.setOnClickListener(this);
        commentbt.setOnClickListener(this);
        searchbutton.setOnClickListener(this);
        searchtype.setOnClickListener(this);

        searchbackimg.setOnClickListener(this);

        List<ServiceContent.DataBean.OtherServiceBean> gridlist = new ArrayList<>();

        adapter = new SearchGridAdapter(this,gridlist);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_distancebt:
                condition = 1;
                distancebt.setSelected(true);
                numberbt.setSelected(false);
                commentbt.setSelected(false);
                viewFragment(0);
                break;
            case R.id.search_bunberbt:
                condition = 2;
                distancebt.setSelected(false);
                numberbt.setSelected(true);
                commentbt.setSelected(false);
                viewFragment(1);
                break;
            case R.id.search_commentbt:
                condition = 3;
                distancebt.setSelected(false);
                numberbt.setSelected(false);
                commentbt.setSelected(true);
                viewFragment(2);
                break;
            case R.id.home_search_back:
                finish();
                break;
            case R.id.search_button:
                con = String.valueOf(searchcontent.getText());
                fast.setVisibility(View.GONE);
                if (TYPE==0){
                    fragmentRoots.setVisibility(View.VISIBLE);
                    searchtab.setVisibility(View.VISIBLE);
                    history.setVisibility(View.GONE);
                    distanceFragment.list.clear();
                    distanceFragment.searchService(fwpage);
                }else if (TYPE==1){
                    SearchShop(dppage);
                    fragmentRoots.setVisibility(View.GONE);
                    searchtab.setVisibility(View.GONE);
                    history.setVisibility(View.VISIBLE);
                }else if (TYPE==3){
                    fragmentRoots.setVisibility(View.VISIBLE);
                    searchtab.setVisibility(View.VISIBLE);
                    history.setVisibility(View.GONE);
                    distanceFragment.list.clear();
                    distanceFragment.searchService(fwpage);
                }else if (TYPE==2){
                   // SearchShop(dppage);
                    searchLocationStore(dppage);
                    fragmentRoots.setVisibility(View.GONE);
                    searchtab.setVisibility(View.GONE);
                    history.setVisibility(View.VISIBLE);
                }else {}
                break;
            case R.id.search_type:
                View view = HomeSearchActivity.this.getLayoutInflater().inflate(R.layout.search_pop, null,true);
                LinearLayout popbac = (LinearLayout) view.findViewById(R.id.pop_bac);
                LinearLayout popshop = (LinearLayout) view.findViewById(R.id.pop_shop);
                LinearLayout popgps = (LinearLayout) view.findViewById(R.id.pop_gps);
                LinearLayout popserce = (LinearLayout) view.findViewById(R.id.pop_service);
                popbac.setAlpha(0.7f);
                final PopupWindow window = new PopupWindow(view, 150, 220,true);
                window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
                window.setFocusable(true);
                window.setOutsideTouchable(true);
                window.update();
                window.showAsDropDown(searchtype, 0, 30);
                window.setBackgroundDrawable(new BitmapDrawable());
                popserce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchtype.setText("服务");
                        TYPE=0;
                        window.dismiss();
                    }
                });
                popshop.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TYPE=1;
                        searchtype.setText("店铺");
                        window.dismiss();
                    }
                });
                popgps.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TYPE=2;
                        searchtype.setText("定点");
                        window.dismiss();
                        fast.setVisibility(View.VISIBLE);
                        searchcontent.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                // 当内容变化是 调用poi 搜索
                                getPOIData(String.valueOf(s));
                            }

                            @Override
                            public void afterTextChanged(Editable s) {

                            }
                        });
                    }
                });
                break;
        }
    }
        // 定点搜索
    private void searchLocationStore(int no) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SEARCHLOCATIONSTORE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        object.put("pageNo",no+"");
        object.put("pageSize","20");
        object.put("longitude",poilongitude1+"");
        object.put("latitude",poilatitude1+"");

        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 顶点搜索--"+result);
                getShopData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onError: 顶点搜索--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getPOIData(String s) {
        PoiSearch.Query query = new PoiSearch.Query(s, "", "");
        query.setPageSize(15);
        PoiSearch search = new PoiSearch(this,query);
        search.setOnPoiSearchListener(this);
        search.searchPOIAsyn();

    }
    // 搜索店铺

    int dppage = 1;
    public String shopString;

    public void SearchShop(int dppage) {

        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETSHOPLIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();
        if(con!=""&con!=null){
            object.put("searchContent",con);
            object.put("pageNo",dppage+"");
            object.put("pageSize","20");
        }else {}
        object.put("longitude",longitude);
        object.put("latitude",latitude);
        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                shopString = result;
                getShopData(result);
                listview.onRefreshComplete();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listview.onRefreshComplete();
                ErrType.errType(HomeSearchActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
        // 店铺数据
    private void getShopData(String result) {
        final List<ShopContent.DataBean> list = new ArrayList<>();
        JSONObject obj1 = JSON.parseObject(result);
        data = obj1.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj2 = JSON.parseObject(String.valueOf(data.get(i)));
            String amount = obj2.getString("amount");
            String distance = obj2.getString("distance");
            String id = obj2.getString("id");
            String name = obj2.getString("name");
            String score = obj2.getString("score");
            String avatar = obj2.getString("avatar");
            String volume = obj2.getString("volume");
            String sellGrade = obj2.getString("sellGrade");
            String isInsurance = obj2.getString("isInsurance");
            String type = obj2.getString("type");
            String gradeCode = obj2.getString("gradeCode");
            DecimalFormat    df   = new DecimalFormat("######0.00");
            String ddd = df.format(Double.valueOf(distance));

            ShopContent.DataBean dataBean = new ShopContent.DataBean();
            dataBean.setGradeCode(Integer.valueOf(gradeCode));
            if (isInsurance.equals("true")){
                dataBean.setIsInsurance(true);
            }else {
                dataBean.setIsInsurance(false);
            }
            dataBean.setSellGrade(Integer.valueOf(sellGrade));
            dataBean.setType(Integer.valueOf(type));
            dataBean.setAvatar(avatar);
            dataBean.setDistance(Double.valueOf(distance));
            dataBean.setId(id);
            dataBean.setVolume(Integer.valueOf(volume));
            dataBean.setName(name);
            list.add(dataBean);
        }
        shopAdapter = new SearchShopAdapter(HomeSearchActivity.this,list);
        listview.setAdapter(shopAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShopContent.DataBean dataBean = (ShopContent.DataBean) shopAdapter.getItem(position-1);
                String id1 = dataBean.getId();
                Intent intent = new Intent(HomeSearchActivity.this,FWShopActivity.class);
                intent.putExtra("id",id1);
                startActivity(intent);
            }
        });
        listview.setMode(PullToRefreshBase.Mode.BOTH);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (data.size()!=0&&data.size()==20){
                    dppage++;
                    list.clear();
                    SearchShop(dppage);
                }else {
                    list.clear();
                    SearchShop(dppage);
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (dppage>1){
                    dppage--;
                    list.clear();
                    SearchShop(dppage);
                }else {
                    list.clear();
                    SearchShop(dppage);
                }
            }
        });
        shopAdapter.notifyDataSetChanged();

    }


    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        ArrayList<PoiItem> pois = poiResult.getPois();
        for (int j = 0; j < pois.size(); j++) {
            String title = pois.get(j).getTitle();
            String snippet = pois.get(j).getSnippet();
            LatLonPoint latLonPoint = pois.get(j).getLatLonPoint();
            double latitude = latLonPoint.getLatitude();
            double longitude = latLonPoint.getLongitude();
        }
        final PoiSearchAdapter adapter = new PoiSearchAdapter(this,pois);
        locationlist.setAdapter(adapter);
        locationlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                searchcontent.setText(adapter.pois.get(position).getTitle());
                poilatitude1 = adapter.pois.get(position).getLatLonPoint().getLatitude();
                poilongitude1 = adapter.pois.get(position).getLatLonPoint().getLongitude();


            }
        });
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
